package cn.chendd.helloclient;

import lombok.SneakyThrows;
import org.apache.commons.lang3.RandomStringUtils;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

/**
 * @author chendd
 */
public class HelloProxyHandler implements InvocationHandler {

    private final Class<?> interfaceClass;

    public HelloProxyHandler(Class<?> interfaceClass){
        this.interfaceClass = interfaceClass;
    }

    @SneakyThrows
    @Override
    public Object invoke(Object object, Method method, Object[] args) {

        if (method.equals(Object.class.getDeclaredMethod("equals", Object.class))) {
            return (Boolean) (object == args[0]);
        } else if (method.equals(Object.class.getDeclaredMethod("hashCode"))) {
            return (Integer) System.identityHashCode(object);
        } else if (method.equals(Object.class.getDeclaredMethod("toString"))) {
            return String.format("%s@%s" , interfaceClass.getSimpleName() , RandomStringUtils.randomAlphanumeric(8).toLowerCase());
        }

        final HelloClient helloClient = interfaceClass.getDeclaredAnnotation(HelloClient.class);
        if (args == null || args.length == 0) {
            return String.format("hello：%s，方法名称：%s，方法参数：无" , helloClient.value() , method.getName());
        }
        StringBuilder builder = new StringBuilder("hello：").append(helloClient.value())
                .append("，方法名称：").append(method.getName()).append("，方法参数：");
        for (Object arg : args) {
            builder.append(arg).append('、');
        }
        builder.deleteCharAt(builder.length() - 1);
        return builder.toString();
    }

}
